package com.zhijiaoyun.adapter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhijiaoyun.oss.UserManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zhijiaoyun.common.CommonUtils;
import com.zhijiaoyun.common.DsConstant;
import com.zhijiaoyun.common.StringUtils;
import com.zhijiaoyun.service.IUserInfoService;
import com.zhijiaoyun.service.IUserService;

/**
 * @author shisfish
 * @date 2017/6/6
 */
public class ApiInterceptorAdapter extends HandlerInterceptorAdapter {

	@Resource
	private IUserService userService;

	@Resource
	private IUserInfoService userInfoService;

	/**
	 * 不需要拦截的内容
	 */
	public String[] allowUrls;

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws IOException {

		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
		int indexOf = requestUrl.indexOf("?");
		if (indexOf != -1) {
			requestUrl = requestUrl.substring(0, indexOf);
		}


		// 如果有允许通过的url 则直接通过
		if (null != allowUrls && allowUrls.length >= 1) {
			for (String url : allowUrls) {
				if (requestUrl.equals(url)) {
					return true;
				}
			}
		}


		
		Map<String, Object> map = new HashMap<>();
		Object token = request.getParameter("token");
		if (StringUtils.isEmptyObject(token)) {
			map.put(DsConstant.CODE, DsConstant.CODE_TOKEN_LOST);
			map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_TOKEN_LOST);
			CommonUtils.responseOutMap(response, map);
			return false;
		}

		boolean flag = UserManager.checkToken(request, response);
		if (!flag) {
			map.put(DsConstant.CODE, DsConstant.CODE_TOKEN_LOST);
			map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_TOKEN_LOST);
			CommonUtils.responseOutMap(response, map);
			return false;
		}

		long userId = CommonUtils.getUserIdByToken(String.valueOf(token));
		if (userId == 0) {
			map.put(DsConstant.CODE, DsConstant.CODE_TOKEN_LOST);
			map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_TOKEN_LOST);
			CommonUtils.responseOutMap(response, map);
			return false;
		}
		request.setAttribute("userId", userId);
		
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

}
